import React, { useState } from 'react';
import 'antd/dist/antd.css';
import Edit from '../CKEditor/Edit'
import {url} from '../../util/config'
import {
    message,
    Upload,
    Form,
    Input,
    Button,
    Select,
    InputNumber,
    Spin,
} from 'antd';
import { UploadOutlined, InboxOutlined } from '@ant-design/icons';
import API from "../../api/api";
import LayoutManage from "../Layout/LayoutManage";
import SelectLayoutArea from "../Layout/SelectLayoutArea";
import './index.css'

const { Option } = Select;
let config = require('../../util/config').config

const normFile = (e) => {
    console.log('Upload event:', e);
    // alert(e)
    if (Array.isArray(e)) {
        return e;
    }
    return e && e.fileList;
};

// 增加目录
export function FormForModule(props){

    const [form] = Form.useForm();

    let [loading,setLoading] = useState(false)

    let hasFlashed = false;

    let [status,setStatus] = useState('N');

    let [sortNum,setSortNum] = useState(null);

    const onReset = () => {
        // alert("reset")
        form.resetFields();
        setStatus('N')
    };

    function closeSpan(){
        setLoading(false)
    }

    const onFinish = (values) => {
        if(values.sortNum==null){
            values.sortNum=undefined
        }
        setLoading(true)
        values.moduleParentId = props.data[1]
        values.moduleType = props.type
        if(props.type=="folder-d"){
            values.layoutParams = JSON.parse(localStorage.getItem("params"))
            values.layoutType = JSON.parse(localStorage.getItem("layoutType"))
        }else {
            values.layoutArea = JSON.parse(localStorage.getItem("layoutArea"))
        }
        console.log('Received values of form: ', values);
        if(API.insertModule(values)=="ok"){
            if(!hasFlashed){
                //只有返回成功后，才会置父组件的状态值为true，即Modal关闭后实现列表刷新
                props.result(true)
                //执行上一步后，再本组件也加一个标记，来标识已经重置了父组件的刷新状态值status
                hasFlashed = true;
            }
        }
        closeSpan()
    };

    function onChange(value) {
        if( typeof value != "number"){
            return
        }
        let tmpStatus = API.sortNum({
                id:props.data[1],
                sortNum:value
            })
        if(tmpStatus=='Y'){
            setStatus('Y')
            setSortNum(value);
        }else {
            setStatus('N')
        }
        console.log('changed', value);
    }
    console.log('props:', props);
    return (
        <Spin spinning={loading}>
            <Form
                preserve={false}
                form={form}
                onFinish={onFinish}
                onReset={onReset}
                labelCol={{
                    span: 4,
                }}
                wrapperCol={{
                    span: 17,
                }}
                layout="horizontal"
            >
                <Form.Item label={props.type=="folder-d"?"菜单名称":(props.type=="file-d"?"文件库名称":(props.type=="article-d"?"文章库名称":(props.type=="page"?"名称":null)))}
                           name={"moduleName"}
                           rules={[{ required: true },
                                   ({ getFieldValue }) => ({
                                       validator(_, value) {
                                           if(value!=undefined && value!=""){
                                               const values = {
                                                   parentId:props.data[1],
                                                   type:props.type,
                                                   value:value
                                               }
                                               const status = API.judgeModule(values)
                                               if(status=="Y"){
                                                   return Promise.reject(new Error('命名冲突!'));
                                               }else if(status=="网络异常"){
                                                   return Promise.reject(new Error('网络异常!'));
                                               }else if(status=='N'){
                                                   return Promise.resolve();
                                               }
                                           }else {
                                               return Promise.resolve();
                                           }
                                       },
                                   })
                           ]}
                >
                    <Input />
                </Form.Item >
                {/*<Form.Item label="菜单类型" name={"moduleType"} rules={[{ required: true }]}>*/}
                {/*    <Select>*/}
                {/*        <Select.Option value="folder-d">{config.folder_d}</Select.Option>*/}
                {/*        {props.data[1]==0 ? null : <Select.Option value="file-d">{config.file_d}</Select.Option>}\*/}
                {/*        {props.data[1]==0 ? null : <Select.Option value="article-d">{config.article_d}</Select.Option>}*/}
                {/*    </Select>*/}
                {/*</Form.Item>*/}
                <Form.Item label="排序" name="sortNum"  validateStatus={status=='Y'? "warning":null} help={status=='Y'?`序号冲突，提交会将该笔数据序号置为${sortNum}` : null }>
                    <InputNumber min={1} onChange={onChange}/>
                </Form.Item>
                <Form.Item label="备注" name={"moduleDesc"}>
                    <Input />
                </Form.Item>
                {
                    props.type=="folder-d"
                        ?
                        <>
                            <LayoutManage layoutParams={props.layoutParams} type="folder-d" storeParams={true} data={props.data}></LayoutManage>
                        </>
                        :
                        null
                }
                {
                    props.type=="file-d" || props.type=="article-d" || props.type=="page"
                        ?
                        <Form.Item label="选择区域" name="layoutArea">
                            <SelectLayoutArea visible={true} type="insert" layoutParams={props.layoutParams}></SelectLayoutArea>
                        </Form.Item>
                        :
                        null
                }
                {
                    props.type=="page"
                        ?
                        <>
                            <Form.Item className="second" label="二級分類" name="secondLayerType">
                                <Select defaultValue="editor" style={{ width: 120 }} >
                                    <Option value="editor">編輯器</Option>
                                    <Option value="itemManage">專案管理</Option>
                                </Select>
                            </Form.Item>
                            <Form.Item className="pageEditorBorder" label="编辑" name="pageContent">
                                <Edit></Edit>
                            </Form.Item>
                        </>
                        :
                        null
                }
                <Form.Item
                    label="提交"
                    name="commit"
                >
                    <Button type="primary" htmlType="submit">
                        提交
                    </Button>
                    <Button htmlType="reset" style={{marginLeft:"1rem"}}>
                        重置
                    </Button>
                </Form.Item>
            </Form>
        </Spin>
    );
};

// 增加文件
export function FormForFile(props){

    const [form] = Form.useForm();
    let [fileVisible,setFileVisible] = useState(false)
    let [articleVisible,setArticleVisible] = useState(false)
    let [folderVisible,setFolderVisible] = useState(false)
    let [editorVisible,setEditorVisible] = useState(null)
    let [uploadList,setUploadList] = useState([])
    let [insertType,setInsertType] = useState(null)
    let [allowOverride,setAllowOverride] = useState(false)
    let [fileList,setFileList] = useState([])
    let [uploading,setUploading] = useState(false)
    let [status,setStatus] = useState('N')

    let hasFlashed = false;

    function onReset(){
        // alert("reset")
        setFileList([])
        form.resetFields();
    };

    function onFinish(values){
        console.log("Component ModulePage ModuleManage",values)
        if(props.data[0]=="article"){
            if(editorVisible==null|| editorVisible=="<p></p>"){
                alert("文章内容不可为空")
                return
            }
            else {
                values.content = editorVisible;
            }
        }
        if(values.new==undefined || values.new==null || values.new == ""){
            values.new = config.notify_date
        }
        values.moduleParentId = props.data[1]
        //file article或者 folder-f
        if(props.data[0]=="file"){
            values.moduleType = "file-d"
            values.fileList = fileList
        } else if(props.data[0]=="article"){
            values.fileType = "article"
            values.moduleType = "article-d"
        } else if(props.data[0]=="folder-f"){
            values.moduleType = "folder"
            values.fileList = fileList
        }
        console.log('Received values of form: ', values);
        if(API.insertFile(values)=="ok"){
            if(!hasFlashed){
                //只有返回成功后，才会置父组件的状态值为true，即Modal关闭后实现列表刷新
                props.result(true)
                //执行上一步后，再本组件也加一个标记，来标识已经重置了父组件的刷新状态值status
                hasFlashed = true;
            }
        }
    };

    function getContent(content) {
        // data = content
        setEditorVisible(content)
    }

    function handleChange(value) {
        setInsertType(value);
        if(value==="file"){
            setFileVisible(true);
            setArticleVisible(false);
            setFolderVisible(false)
        }
        else if(value=="article"){
            setArticleVisible(true);
            setFileVisible(false)
            setFolderVisible(false)
        }else {
            setFolderVisible(true)
            setArticleVisible(false);
            setFileVisible(false)
        }
        console.log(`selected ${value}`);
    }

    let token = localStorage.getItem("token")

    const request = {
        // action: "http://localhost:8081/upload",
        // action: url.file_upload_url+"Opt",
        action: url.file_upload_url,
        headers: {
            'Accept': "application/json",
            'Authorization': token
        }
    }

    const insertFileProps = {
        onRemove: (file) => {
            setFileList((state) => {
                const index = fileList.indexOf(file);
                const newFileList = fileList.slice();
                newFileList.splice(index, 1);
                return newFileList;
            });
        },
        beforeUpload: (file) => {
            let tmpFileList = fileList
            tmpFileList.push(file)
            setFileList(tmpFileList)
            return false;
        }
    }
    console.log("props:",props)
    return (
        <Form
            preserve={false}
            form={form}
            onFinish={onFinish}
            onReset={onReset}
            labelCol={{
                span: 4,
            }}
            wrapperCol={{
                span: 17,
            }}
            layout="horizontal"
            initialValues={{
                ['new']: config.notify_date
            }}
        >
            {props.data[0]!="article"
                ?
                <Form.Item label="添加类型" name="fileType" rules={[{ required: true }]}>
                    <Select onChange={handleChange}>
                        <Select.Option value="file">文件</Select.Option>
                        <Select.Option value="folder">文件夹</Select.Option>
                    </Select>
                </Form.Item>
                :
                <Form.Item label={ props.data[0]=="article" ? "文章名称" : null}
                           name="fileName"
                           rules={[{ required: true },
                                   ({ getFieldValue }) => ({
                                       validator(_, value) {
                                           const values = {
                                               parentType:'article-d',
                                               parentId:props.data[1],
                                               type:'article',
                                               value:value
                                           }
                                           if(value!=undefined && value!=""){
                                               const status = API.judgeFolderAndArticle(values)
                                               if(status=="Y"){
                                                   return Promise.reject(new Error('命名冲突!'));
                                               }else if(status=="网络异常"){
                                                   return Promise.reject(new Error('网络异常!'));
                                               }else if(status=='N'){
                                                   return Promise.resolve();
                                               }
                                           }else {
                                               return Promise.resolve();
                                           }
                                       },
                                   })
                           ]}>
                    <Input />
                </Form.Item>
            }
            {
                folderVisible==true
                ?
                <Form.Item label="文件夹名称"
                           name="fileName"
                           // hasFeedback
                           rules={[{ required: true,message: "请输入文件夹名称" },
                                   ({ getFieldValue }) => ({
                                       validator(_, value) {
                                           const values = {
                                               parentType:props.data[0],
                                               parentId:props.data[1],
                                               type:'folder',
                                               value:value
                                           }
                                           if(value!=undefined && value!=""){
                                               const status = API.judgeFolderAndArticle(values)
                                               if(status=="Y"){
                                                  return Promise.reject(new Error('命名冲突!'));
                                               }else if(status=="网络异常"){
                                                  return Promise.reject(new Error('网络异常!'));
                                               }else if(status=='N'){
                                                   return Promise.resolve();
                                               }
                                           }else {
                                               return Promise.resolve();
                                           }
                                       },
                                   })
                                 ]}
                >
                    {/*<Input onChange={(value)=>{*/}
                    {/*    const values = {*/}
                    {/*        parentType:props.data[0],*/}
                    {/*        parentId:props.data[1],*/}
                    {/*        type:'folder',*/}
                    {/*        value:value*/}
                    {/*    }*/}
                    {/*    setStatus(API.judgeFolderAndArticle(values)) }}*/}
                    {/*/>*/}
                    <Input/>
                </Form.Item>
                :
                null
            }
            <Form.Item label="提醒時間【天數】" name="new">
                <InputNumber min={1} placeholder={`默認${config.notify_date}天`}/>
            </Form.Item>
            <Form.Item label="是否置顶" name="fileTopStatus">
                <Select>
                    <Select.Option value="Y">是</Select.Option>
                    <Select.Option value="N">否</Select.Option>
                </Select>
            </Form.Item>
            <Form.Item label={props.data[0]=="article"?"文章备注":"文件备注"} name="fileDesc" >
                <Input />
            </Form.Item>
            {
                fileVisible === true ?
                    <>
                        <Form.Item
                            name="allowOverride"
                            label="覆盖重名文件"
                        >
                            <Select defaultValue="false" style={{ width: 120 }} >
                                <Option value="true">允许</Option>
                                <Option value="false">禁止</Option>
                            </Select>
                            {/*<span>  【 默认禁止重名文件上传 】</span>*/}
                        </Form.Item>
                        <Form.Item
                            name="upload"
                            label="文件上传"
                            valuePropName="fileList"
                            getValueFromEvent={normFile}
                            rules={[{ required: true }]}
                        >
                            <Upload name="file" multiple={true} {...insertFileProps} listType="picture">
                                <Button icon={<UploadOutlined />}>上传</Button>
                            </Upload>
                        </Form.Item>
                    </>
                    :
                    null
            }
            {
                articleVisible === true || props.data[0]=="article"?
                    <>
                        <Form.Item
                            name="upload"
                            label="附件上传"
                            valuePropName="fileList"
                            getValueFromEvent={normFile}
                        >
                            <Upload name="file" {...request} listType="picture">
                                <Button icon={<UploadOutlined />}>上传</Button>
                            </Upload>
                        </Form.Item>
                        <Form.Item
                            name="edit"
                            label="文章编辑"
                            rules={[{ required: true }]}
                        >
                            {/*<Button onClick={_=>alert(editorVisible)}>获取文件内容</Button>*/}
                            <Edit onChange={getContent}></Edit>
                        </Form.Item>
                    </>
                    :
                    null
            }
            <Form.Item
                label="提交添加"
                name="commit"
            >
                <Button type="primary" htmlType="submit">
                    提交
                </Button>
                <Button htmlType="reset" style={{marginLeft:"1rem"}}>
                    重置
                </Button>
            </Form.Item>
        </Form>
    );
};
